import echarts from 'echarts'

export default {
  filters: {
    _this: this,
    num2numStr (num) {
      num = num + ''
      if (num.indexOf('.') !== -1) {
        return num
      } else {
        let numbers = num.split('').reverse()
        let numStr = ''
        numbers.forEach((num, index) => {
          if (index !== 0 && index % 3 === 0) {
            numStr = num + '' + numStr
          } else {
            numStr = num + '' + numStr
          }
        })
        return numStr
      }
    }
  },
  data () {
    return {
      timer: null,
      // 空间的 树形 数组
      ensTreeData: [],
      workSpaceTip: '',
      // 各个接口的 需要的参数
      overviewForm: {
        spaceValue: []
      },
      workSpaceString: '',
      // 左侧 下面的 俩个 折线图
      totalLineChartData: {
        xAxisData: ['', '', '', '', '', '', '', '', '', '', '', ''],
        seriesData: [120, 132, 101, 134, 90, 230, 210, 120, 132, 101, 134, 90]
      },
      averageTempChartLineData: {
        xAxisData: ['', '', '', '', '', '', '', '', '', '', '', ''],
        seriesData: [120, 132, 101, 134, 90, 230, 210, 120, 132, 101, 134, 90]
      },
      // end
      // 类型占比/排行用的 字段
      typePercent: [],
      pieColors: ['#3C30F5', '#2EA0F7', '#F83F59', '#2378FF', '#49C8EB', '#EFAD0E', '#A466F7', '#0BF535', '#c23531', '#2f4554', '#61a0a8', '#d48265', '#91c7ae', '#749f83', '#ca8622', '#bda29a', '#6e7074', '#546570', '#c4ccd3', '#66CD00', '#668B8B', '#8B1C62', '#8B0000', '#87CEEB', '#7EC0EE', '#B8860B', '#B4EEB4', '#D2B48C', '#DA70D6', '#DEB887', '#F5FFFA', '#00CED1', '#104E8B', '#43CD80', '#36648B', '#1E90FF', '#0D0D0D', '#00EE76', '#009ACD'],
      // 子级占比/排行用的 字段
      childTypePercent: [],
      childPieColors: ['#3C30F5', '#2EA0F7', '#F83F59', '#2378FF', '#49C8EB', '#EFAD0E', '#A466F7', '#0BF535', '#c23531', '#2f4554', '#61a0a8', '#d48265', '#91c7ae', '#749f83', '#ca8622', '#bda29a', '#6e7074', '#546570', '#c4ccd3', '#66CD00', '#668B8B', '#8B1C62', '#8B0000', '#87CEEB', '#7EC0EE', '#B8860B', '#B4EEB4', '#D2B48C', '#DA70D6', '#DEB887', '#F5FFFA', '#00CED1', '#104E8B', '#43CD80', '#36648B', '#1E90FF', '#0D0D0D', '#00EE76', '#009ACD'],
      // end
      // 走势 折线图
      chartLineData: {
        xAxisData: [],
        yieldData: [],
        carbonData: []
      },
      // childPie 的饼图 title of text
      childPieTitle: '',
      // 4月24日 新版需要新添加的 参数
      workSpaceName: '',
      // 控制总量 还是 单车的
      selectType: true,
      // 7月11日 的浏览器刷新定时器
      browserTimer: null
    }
  },
  methods: {
    // 选择后展示的函数，用于自定义显示格式
    format (labels, selectedData) {
      let str = ''
      for (let i = 0; i < selectedData.length; i++) {
        if (!i) {
          str = selectedData[i].value
        } else {
          str = str + ' - ' + selectedData[i].value
        }
      }
      return str
    },
    // 过滤 数字 有 , 的方法
    _num2numStr (num) {
      num = num + ''
      if (num.indexOf('.') !== -1) {
        return num
      } else {
        let numbers = num.split('').reverse()
        let numStr = ''
        numbers.forEach((num, index) => {
          if (index !== 0 && index % 3 === 0) {
            numStr = num + ',' + numStr
          } else {
            numStr = num + '' + numStr
          }
        })
        return numStr
      }
    },
    // 左侧 边缘 的 折线图
    // initTotalLineChart () {
    //   let dom = this.$refs.totalLineChart
    //   let myChart = echarts.init(dom[0])
    //   let option = null
    //   let totalLineChartData = this.totalLineChartData
    //   option = this.mLineChartOption({
    //     xAxisData: totalLineChartData.xAxisData || ['', '', '', '', '', '', '', '', '', '', '', ''],
    //     seriesData: totalLineChartData.seriesData || [120, 132, 101, 134, 90, 230, 210, 120, 132, 101, 134, 90],
    //     lineColor: '#687FF5',
    //     areaColor: '#283B86'
    //   })
    //   if (option && typeof option === 'object') {
    //     myChart.setOption(option, true)
    //   }
    // },
    // initAverageTempLineChart () {
    //   let dom = this.$refs.averageTempLineChart
    //   let myChart = echarts.init(dom[0])
    //   let option = null
    //   let averageTempChartLineData = this.averageTempChartLineData
    //   option = this.mLineChartOption({
    //     xAxisData: averageTempChartLineData.xAxisData || ['', '', '', '', '', '', '', '', '', '', '', ''],
    //     seriesData: averageTempChartLineData.seriesData || [120, 132, 101, 134, 90, 230, 210, 120, 132, 101, 134, 90],
    //     lineColor: '#DC4A64',
    //     areaColor: '#593058'
    //   })
    //   if (option && typeof option === 'object') {
    //     myChart.setOption(option, true)
    //   }
    // },
    // end
    // 类型占比/排名 的饼图 方法
    initPieChart (title) {
      let dom = this.$refs.pieChart
      let myChart = echarts.init(dom)
      let option = null
      option = {
        title: {
          text: `${this.selectType ? '总' : '单车'}${title}\n\n  ${this._num2numStr(this.typePercentTotal)}`,
          textVerticalAlign: 'middle',
          textStyle: {
            color: '#fff',
            fontWeight: 'normal'
          },
          width: 200,
          height: 50,
          textAlign: 'center',
          left: '48%',
          top: '40%'
        },
        tooltip: {
          show: true,
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        series: [
          {
            name: '类型占比/排名',
            type: 'pie',
            radius: ['67%', '90%'],
            avoidLabelOverlap: false,
            label: {
              normal: {
                show: false,
                position: 'center'
              },
              emphasis: {
                show: false,
                textStyle: {
                  fontSize: '18'
                },
                formatter: [
                  '{b}\n',
                  '{c}'
                ].join('\n')
              },

              color: '#000'
            },
            labelLine: {
              normal: {
                show: false
              }
            },
            emphasis: {},
            itemStyle: {
              borderWidth: 5,
              borderType: 'solid',
              borderColor: 'rgba(22, 44, 99,0)'
              // shadowColor: 'rgba(0, 0, 0, 0.5)',
              // shadowBlur: 10
            },
            data: []
          }
        ]
      }
      // 饼图 样式 的修改
      if (!this.typePercent.length) {
        option.title.text = ''
      } else {
        // 给饼 图 每个 对象 添加 不同的样式
        let typePercent = this.typePercent
        typePercent = typePercent.map((item, index) => {
          let obj = {
            name: item.name,
            value: item.value,
            itemStyle: {color: this.pieColors[index]},
            label: {color: '#fff'}
          }
          return obj
        })
        option.series[0].data = typePercent
      }
      if (option && typeof option === 'object') {
        myChart.setOption(option, true)
      }
    },
    // 子级占比/排名 的饼图
    childInitPieChart () {
      let dom = this.$refs.childPieChart
      let myChart = echarts.init(dom)
      let option = null
      option = {
        title: {
          text: `${this.childPieTitle}\n\n` + this._num2numStr(this.childTypePercentTotal),
          textVerticalAlign: 'middle',
          textStyle: {
            color: '#fff',
            fontWeight: 'normal'
          },
          width: 200,
          height: 50,
          textAlign: 'center',
          left: '48%',
          top: '40%'
        },
        tooltip: {
          show: true,
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        series: [
          {
            name: '子级占比/排名',
            type: 'pie',
            radius: ['67%', '90%'],
            avoidLabelOverlap: false,
            label: {
              normal: {
                show: false,
                position: 'center'
              },
              emphasis: {
                show: false,
                textStyle: {
                  fontSize: '18'
                },
                formatter: [
                  '{b}\n',
                  '{c}'
                ].join('\n')
              },

              color: '#000'
            },
            labelLine: {
              normal: {
                show: false
              }
            },
            emphasis: {},
            itemStyle: {
              borderWidth: 5,
              borderType: 'solid',
              borderColor: 'rgba(22, 44, 99,0)'
              // shadowColor: 'rgba(0, 0, 0, 0.5)',
              // shadowBlur: 10
            },
            data: []
          }
        ]
      }
      // 饼图 样式 的修改
      if (!this.childTypePercent.length) {
        option.title.text = ''
      } else {
        // 给饼 图 每个 对象 添加 不同的样式
        let childTypePercent = this.childTypePercent
        let other = childTypePercent.findIndex(item => item.name === '其他')
        if (other > -1) {
          childTypePercent.push(childTypePercent.splice(other, 1)[0])
        }
        childTypePercent = childTypePercent.map((item, index) => {
          let obj = {
            name: item.name,
            value: item.value,
            itemStyle: {color: this.childPieColors[index]},
            label: {color: '#fff'}
          }
          return obj
        })
        option.series[0].data = childTypePercent
      }
      if (option && typeof option === 'object') {
        myChart.setOption(option, true)
      }
    },
    // 走势 折线图的方法
    initCompareLine (name) {
      let dom = this.$refs.compareLineChart
      let myChart = echarts.init(dom)
      let option = null
      option = {
        title: {
          show: false
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'line'
          },
          backgroundColor: '#fff',
          textStyle: {
            color: '#333',
            fontSize: 12
          }
        },
        legend: {
          show: false
        },
        toolbox: {
          feature: {}
        },
        grid: {
          left: '65px',
          right: '65px',
          bottom: '35px',
          top: '44px',
          containLabel: false
        },
        xAxis: [
          {
            type: 'category',
            boundaryGap: false,
            data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
            axisLine: {
              show: true,
              lineStyle: {
                color: '#8C99B6'
              }
            },
            axisLabel: {
              color: '#fff',
              margin: 20
            },
            axisTick: {
              length: 10,
              lineStyle: {
                color: '#8C99B6'
              }
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            show: true,
            name: '',
            nameTextStyle: {
              color: '#fff',
              padding: [10, 20]
            },
            // scale: true,
            position: 'left',
            splitLine: {
              lineStyle: {
                type: 'dashed',
                show: false,
                color: '#8C99B6',
                opacity: 0
              }
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#8C99B6'
              }
            },
            // axisTick: {
            //   length: 0
            // },
            axisLabel: {
              inside: false,
              margin: 15,
              show: true,
              color: '#fff',
              formatter: (value) => {
                if (value >= 10000 && value < 10000000) {
                  value = value / 10000 + '万'
                } else if (value >= 10000000) {
                  value = value / 10000000 + '千万'
                }
                return value
              }
            }
          },
          {
            type: 'value',
            name: '',
            nameTextStyle: {
              color: '#fff',
              padding: [10, 20]
            },
            // show: true,
            // scale: true,
            position: 'right',
            splitLine: {
              lineStyle: {
                type: 'solid',
                show: false,
                color: '#8C99B6',
                opacity: 0
              }
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#8C99B6'
              }
            },
            // axisTick: {
            //   length: 0
            // },
            axisLabel: {
              inside: false,
              margin: 15,
              show: true,
              color: '#fff',
              formatter: (value) => {
                if (value >= 10000 && value < 10000000) {
                  value = value / 10000 + '万'
                } else if (value >= 10000000) {
                  value = value / 10000000 + '千万'
                }
                return value
              }
            }
          }
        ],
        series: [
          {
            name: '实际',
            smooth: true,
            type: 'line',
            yAxisIndex: 0,
            // stack: '总量',
            color: '#43CCBA',
            lineStyle: {
              color: '#43CCBA'
            },
            areaStyle: {
              color: '#246198'
            },
            data: []
          },
          {
            name: '计划',
            smooth: true,
            type: 'line',
            yAxisIndex: 1,
            // stack: '总量',
            color: '#7489F6',
            lineStyle: '#7489F6',
            areaStyle: {
              color: '#2B4298'
            },
            data: []
          }
        ]
      }
      // let compareData = this.compareData;
      // let xAisData = this.compareData.xAisData;
      // let seriesDatas = this.compareData.seriesDatas;
      let chartLineData = this.chartLineData
      let xAisData = chartLineData.xAxisData
      let seriesDatas = [chartLineData.yieldData, chartLineData.carbonData]
      option.xAxis[0].data = xAisData
      seriesDatas.forEach((serie, index) => {
        if (index <= 1) {
          option.series[index].data = serie
        }
      })
      // 7月16日 新需求更改优化
      if (chartLineData.yName.length > 0) {
        let [ reality, plan ] = chartLineData.yName
        option.yAxis[0].name = reality
        option.yAxis[1].name = plan
      }
      if (option && typeof option === 'object') {
        myChart.setOption(option, true)
        window.addEventListener('resize', () => {
          myChart.resize()
        })
      }
    },
    // 空间选择  树形数据
    ensTree: function (obj = {}, cb) {
      let self = this
      window.myapi.ensTree(obj).then(function (res) {
        if (res.data.status === 200) {
          self.ensTreeData = res.data.data
          if (self.ensTreeData.length === 0) {
            self.$Message.info('空间架构无数据，请补充数据')
            return false
          } else {
            // 空间的 id  和 workSpaceName 参数
            self.workSpaceString = self.ensTreeData[0].value
            self.workSpaceTip = self.ensTreeData[0].label
            self.workSpaceName = self.ensTreeData[0].label
            // 饼图 显示 名称 的 字段
            self.childPieTitle = self.ensTreeData[0].label
            self.$set(self.overviewForm, 'spaceValue', [self.ensTreeData[0].value])
            cb()
          }
        }
      }).catch(function (e) {
        console.log(e)
      })
    },
    // 空间改变
    changeWorkSpace: function (workSpace, selectedData) {
      let self = this
      let str = ''
      for (let i = 0; i < selectedData.length; i++) {
        if (!i) {
          str = selectedData[i].label
        } else {
          str = str + ' / ' + selectedData[i].label
        }
      }
      self.workSpaceTip = str
      self.workSpaceString = workSpace[workSpace.length - 1]
      self.childPieTitle = selectedData.find(item => self.workSpaceString === item.id).label
      self.workSpaceName = selectedData.map(item => item.label).join('/')
      self.$set(self.overviewForm, 'spaceValue', workSpace)
      self.refreshData()
    },
    // 定时器封装函数
    _timerFun (s) {
      let count = 0
      const time = () => {
        this.timer = setTimeout(() => {
          count += 3
          if (count > 30) {
            clearTimeout(this.timer)
            count = 0
          }
          this.refreshData()
          time()
        }, s)
      }
      time()
    },
    // 7月11日 浏览器刷新定时器封装函数
    _browserTime (s) {
      let count = 0
      const time = () => {
        this.browserTimer = setTimeout(() => {
          count += 3
          if (count > 30) {
            clearTimeout(this.browserTimer)
            count = 0
          }
          window.location.reload()
          time()
        }, s)
      }
      time()
    }
  },
  computed: {
    typePercentTotal () {
      let total = 0
      this.typePercent.forEach(item => {
        total += parseFloat(item.value)
      })
      return total.toFixed(2)
    },
    childTypePercentTotal () {
      return this.childTypePercent.reduce((pre, next) => {
        return pre + parseFloat(next.value)
      }, 0).toFixed(2)
    }
  },
  mounted () {
    this._browserTime(10800000)
  },
  destroyed () {
    clearInterval(this.timer)
    // 7月11日 浏览器定时刷新的
    clearTimeout(this.browserTimer)
  }
}
